package com.harmonyos.fishbun.util;

import com.isotne.glidelibrary.utils.OhosGlide;
import com.sangcomz.fishbun.BaseAbilitySlice;
import com.sangcomz.fishbun.util.MainUiHandler;
import com.sangcomz.fishbun.util.ThreadPoolUtil;
import com.sangcomz.fishbun.util.UiHandler;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.agp.components.Image;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.ImageInfo;
import ohos.media.image.common.Size;
import ohos.utils.net.Uri;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ImageUtil {

    public static void loadImage(AbilitySlice abilitySlice, Image target, Uri loadUrl) {

        ThreadPoolUtil.execute(new Runnable() {
            @Override
            public void run() {
                ImageSource imageSource = null;
                DataAbilityHelper helper = null;

                try {
                    helper = DataAbilityHelper.creator(abilitySlice);
                    FileDescriptor fileDescriptor = helper.openFile(loadUrl, "r");
                    imageSource = ImageSource.create(fileDescriptor, null);
                    ImageInfo imageInfo = imageSource.getImageInfo();
                    Size size = imageInfo.size;

                    ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();

                    decodingOpts.desiredSize = sampleSize(target, size);

                    PixelMap pixelMap = imageSource.createThumbnailPixelmap(decodingOpts, true);

                    new MainUiHandler().run(new UiHandler.RunUIThread() {
                        @Override
                        public void run() {
                            target.setPixelMap(pixelMap);
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (imageSource != null) {
                        imageSource.release();
                    }
                    if (helper != null) {
                        helper.release();
                    }
                }
            }
        });
    }

    public static Size sampleSize(Image image, Size resSize) {
        int imageWidth = image.getWidth() > 0 ? image.getWidth() : 200;
        int imageHeight = image.getHeight() > 0 ? image.getHeight() : 200;

        int resourceWidth = resSize.width;
        int resourceHeight = resSize.height;

        int inSampleSize = Math.min(resourceWidth / imageWidth, resourceHeight / imageHeight);
        if (inSampleSize <= 1) {
            return resSize;
        } else {
            return new Size(resourceWidth / inSampleSize, resourceHeight / inSampleSize);
        }

    }
}
